//
//  RequestEngine.m
//  定制公交
//
//  Created by thinkjoy on 16/4/18.
//  Copyright © 2016年 thinkjoy. All rights reserved.
//

#import "RequestEngine.h"
#import "RSDefineHeaders.h"
#import <AFNetworking/AFNetworking.h>
#import "SecurityUtil.h"
#import "SVProgressHUD.h"
#import "TimeUnit.h"

@interface RequestEngine ()<UIApplicationDelegate>

@end

@implementation RequestEngine

#pragma mark - get 数据请求
- (void) getWithURL:(NSString *)urlString parameterDic:(NSDictionary *)dictionary onSuccess:(void(^)(NSDictionary *_InfoDic))_onSuccess  onError:(void(^)(NSUInteger __errorCode,NSString *__errorMsg))_onError
{
     urlString   =   [[NSString stringWithFormat:@"%@%@",BaseHostURL,urlString]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.requestSerializer   =   [AFHTTPRequestSerializer serializer];
    manager.responseSerializer  =   [AFHTTPResponseSerializer serializer];
    
    NSURL *URL = [NSURL URLWithString:urlString];
    manager.requestSerializer.timeoutInterval = 5.f;   //请求时间
    
    [manager GET:URL.absoluteString parameters:dictionary progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * jsonDic = [SecurityUtil transformResponseObject:responseObject];
        
        DLog(@"jsonDic==%@",jsonDic);
        if (_onSuccess) {
            _onSuccess(jsonDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"%@",error);
        if (_onError) {
            _onError(200,@"error");
        }
        [SVProgressHUD dismiss];
        [self   showRequestError];
        
    }];
    
}

#pragma mark    - POST 登录
- (void)postLoginWithUrl:(NSString *)urlString parameterDic:(NSDictionary *)dictionary onSuccess:(void(^)(NSDictionary *_loginInfo))_onSuccess  onError:(void(^)(NSUInteger __errorCode,NSString *__errorMsg))_onError
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    urlString   =   [[NSString stringWithFormat:@"%@%@",BaseHostURL,urlString]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    
    manager.requestSerializer   =   [AFHTTPRequestSerializer serializer];
    manager.responseSerializer  =   [AFHTTPResponseSerializer serializer];

    NSURL *URL = [NSURL URLWithString:urlString];
    manager.requestSerializer.timeoutInterval = 5.f;   //请求时间

    [manager POST:URL.absoluteString parameters:dictionary progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * jsonDic = [SecurityUtil transformResponseObject:responseObject];

        DLog(@"jsonDic==%@",jsonDic);
        
        //获得请求头中的cookie值,只在第一次登陆中使用,保存在本地,退出登陆时删除掉
//        NSHTTPURLResponse    *  response    =   (NSHTTPURLResponse *)task.response;
//        NSDictionary    * allHeaderFiledsDic    =   response.allHeaderFields;
//        NSString    * cookieStr =   allHeaderFiledsDic[@"Set-Cookie"];
//        [NUD setObject:cookieStr forKey:COOKIEStr];
        
        if (_onSuccess) {
//            _onSuccess(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"%@",error);
        if (_onError) {
            _onError(200,@"error");
        }
        [SVProgressHUD dismiss];
        [self   showRequestError];

    }];
}

#pragma mark - POST 数据请求
- (void) postWithURL:(NSString *)urlString parameterDic:(NSDictionary *)dictionary onSuccess:(void(^)(NSDictionary *_InfoDic))_onSuccess  onError:(void(^)(NSUInteger __errorCode,NSString *__errorMsg))_onError
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    urlString   =   [[NSString stringWithFormat:@"%@%@",BaseHostURL,urlString]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    NSURL *URL = [NSURL URLWithString:urlString];
    manager.requestSerializer.timeoutInterval = 5.f;   //请求时间
    manager.requestSerializer   =   [AFHTTPRequestSerializer serializer];
    manager.responseSerializer  =   [AFHTTPResponseSerializer serializer];
    
    // 返回的类型
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data", nil];
    [manager POST:URL.absoluteString parameters:dictionary progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        //获得请求头中的cookie值,只在第一次登陆中使用,保存在本地,退出登陆时删除掉
//        NSHTTPURLResponse    *  response    =   (NSHTTPURLResponse *)task.response;
//        NSDictionary    * allHeaderFiledsDic    =   response.allHeaderFields;
//        NSString    * cookieStr =   allHeaderFiledsDic[@"Set-Cookie"];
//        [NUD setObject:cookieStr forKey:COOKIEStr];
        NSDictionary * jsonDic = [SecurityUtil transformResponseObject:responseObject];
        if (_onSuccess) {
            _onSuccess(jsonDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_onError) {
            _onError(200,@"error");
        }
        [SVProgressHUD dismiss];
        [self   showRequestError];
    }];
}

#pragma mark - POST 带有请求体的Post请求
- (void) postWithURL:(NSString *)urlString parameterDic:(NSDictionary *)dictionary bodyDic:(NSDictionary *)bodyDic onSuccess:(void(^)(NSDictionary *_InfoDic))_onSuccess  onError:(void(^)(NSUInteger __errorCode,NSString *__errorMsg))_onError
{
    //设置请求体的参数,转化为json并加密
    NSString * msgIDStr =   [NSString stringWithFormat:@"%@%04d",[TimeUnit getNowTimeStrWithNowTimeWithFormatterStyle:@"YYYYMMddHHmmss"],arc4random()%10000];//YYYY-MM-dd HH:mm
    NSString * reqTimeStr   =   [TimeUnit getNowTimeStrWithNowTimeWithFormatterStyle:@"YYYY-MM-dd HH:mm:ss"];
    NSDictionary * bodyAllDic =   @{@"msgId":msgIDStr,
                                    @"reqTime":reqTimeStr,
                                    @"data":bodyDic};
    NSString * bodyAES128Str    =   [SecurityUtil transformDictionaryToAES128JsonStr:bodyAllDic];
    DLog(@"bodyAES128Str===%@",bodyAES128Str);
    
    //设置URL,将普通参数追加到URL中
    urlString   =   [NSString stringWithFormat:@"%@%@?",BaseHostURL,urlString];
    for (int i=0; i<dictionary.allKeys.count; i++) {
        NSString * key = dictionary.allKeys[i];
        NSString * obj = dictionary[key];
        urlString = [NSString stringWithFormat:@"%@%@=%@",urlString,key,obj];
        if (i<dictionary.allKeys.count-1) {
            urlString   =   [urlString stringByAppendingString:@"&"];
        }
    }
    urlString   =   [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    NSURL *URL = [NSURL URLWithString:urlString];
    
    
    //创建请求管理并发送请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 5.f;   //请求时间
    manager.requestSerializer   =   [AFJSONRequestSerializer serializer];
    manager.responseSerializer  =   [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
   
    [manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //添加请求体
        [formData appendPartWithHeaders:nil body:[bodyAES128Str dataUsingEncoding:NSUTF8StringEncoding]];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //解密
        NSDictionary * jsonDic = [SecurityUtil transformResponseObject:responseObject];
        if (_onSuccess&& !IsDicEmpty(jsonDic)) {
            _onSuccess(jsonDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_onError) {
            _onError(200,@"error");
        }
        [SVProgressHUD dismiss];
    }];
}

- (void)showRequestError
{
//    [RSAlertViewManager showAlertViewWithControllerTitle:@"温馨提示" message:@"暂无响应,请稍后再试" controllerStyle:UIAlertControllerStyleAlert isHaveTextField:NO actionTitle:@"确定" actionStyle:UIAlertActionStyleDefault alertViewAction:^(UIAlertAction *action) {
//        
//    }];

}
@end
